package com.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.core.Result;

import java.util.Arrays;
import java.util.List;

public class FastJsonFilter {
    /**
     * @Description:过滤掉不需要返回的字段
     * @Param: [src, clazz, args]`
     * @return java.lang.String
     */
    public static JSONArray excludeFieldsJson(Object src, Class<?> clazz, String... excludesProperties)
    {
        final List<String> excludes = Arrays.asList(excludesProperties);
        PropertyFilter proFileter=new PropertyFilter() {
            @Override
            public boolean apply(Object object, String name, Object value) {
                return !excludes.contains(name);
            }
        };
        return JSON.parseArray(JSON.toJSONString(src,proFileter)) ;
    }
    /**
     * @Description:只返回指定的字段
     * @Param: [src, clazz, args]`
     * @return java.lang.String
     */
    public static JSONArray includeFieldsJson(Object src, Class<?> clazz, String... includes)
    {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(clazz, includes);
        return JSON.parseArray(JSON.toJSONString(src, filter));
    }
    /**
     * @Description:只返回指定的字段
     * @Param: [src, clazz, args]`
     * @return java.lang.String
     */
    public static String ReturnApiResult(Result src)
    {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Result.class, "code","body","message");
        return JSON.toJSONString(src, filter);
    }
}
